import os
import requests
import json
import urllib3
from commond import read_config, log_config, get_path_info


class RunMain(object):
    def __init__(self, config_name, project_name):
        self.readconfig = read_config.ReadConfig(config_name, project_name)
        project_case_path = get_path_info.get_test_project(project_name)
        result_path = os.path.join(project_case_path, "result")
        self.log = log_config.Logger().get_logger(result_path)
        urllib3.disable_warnings()

    def send_post(self, url, data, query_format, headers):  #

        # verify=False hhtps忽略ssl
        if query_format == "form":
            result = requests.post(url=url, verify=False, data=data, headers=headers)
            # print(result)
            return result
        if query_format == "json":
            result = requests.post(url=url, verify=False, json=json.dumps(data), headers=headers)
            # print(result)
            return result
        else:
            self.log.info("请填写参数类型")

    def send_get(self, url, data, query_format, headers):
        # if query_format == "form":
        result = requests.get(url=url, verify=False, data=data, headers=headers)
        print(result)
        return result
        # res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)

    def run_main(self, method, url=None, data=None, query_format=None,
                 headers=None):  # 定义一个run_main函数，通过传过来的method来进行不同的get或post请求
        result = None
        try:
            if method == 'post':
                result = self.send_post(url, data, query_format, headers)
            elif method == 'get':
                result = self.send_get(url, data, query_format, headers)
            else:
                # print("method值错误！！！")
                self.log.info("method值错误！！！")
        except Exception as e:
            self.log.info(e)
        return result
